﻿using MCP.BL.Messages;
using MCP.Model.Helpers;
using MCP.Model.Repositories.Interfaces;
using MoneyCounter.Models;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using client = MCP.Data.Client;

namespace MoneyCounter.Controllers
{
	public class ChecksListController : BaseControllerWithDatasource
	{
	    public ChecksListController(IUnitOfWork unitOfWork)
            : base(unitOfWork)
	    {
	    }

	    public ActionResult ChecksList()
		{
            var model = new ChecksListModel();
		    SimpleMessage noChecksMessage = null;

		    var getChecksResult = this.unitOfWork.CheckRepository.GetChecks();
            
            if (getChecksResult.Success)
            {
                var checks = getChecksResult.Result.ToList();
                if (checks.Any())
                {
                    checks = checks.OrderByDescending(c => c.Date).ToList();
                }
                else
                {
                    noChecksMessage = new SimpleMessage("You currently have no checks. Add new one <a href='/ChecksList/AddNewCheckManualy'>manualy</a>.", MessagePriority.Low, MessageType.Info);
                }

                model.Checks = checks;
            }
            else
            {
                model.Checks = new List<client.Check>();
            }

            model.Messages = getChecksResult.Messages
				.Push(
					CurrentUserHelper.User.GetCurrentBalanceStatus(this.unitOfWork),
					noChecksMessage,
                    new SimpleMessage(string.Format("You currently have {0} checks", model.Checks.Count()), MessagePriority.Low, MessageType.Info));

			return this.View(model);
		}

		/// <summary>
		/// Returns view for "Add new check manualy" page.
		/// </summary>
		/// <returns>View.</returns>
		public ActionResult AddNewCheckManualy()
		{
			var model = new AddNewCheckManualyModel();

		    var getCategoriesResult = this.unitOfWork.CategoryRepository.GetUserCategories();
            if (getCategoriesResult.Success)
            {
                model.Categories = getCategoriesResult.Result;
                model.Messages = getCategoriesResult.Messages ?? MessagePool.Create(new SimpleMessage("Checking", MessagePriority.Medium, MessageType.Notification));
            }

			this.ViewData["Currency"] = ConfigurationManager.AppSettings["Currency"];

			return this.View(model);
		}

		/// <summary>
		/// Adds new manualy added check to DB.
		/// </summary>
		/// <param name="check">Check (client) to add.</param>
		/// <returns>Nothing.</returns>
		public ActionResult AddNewCheck(client.Check check)
		{
			if (check == null || !check.Items.Any()) return new HttpNotFoundResult();

		    //this.unitOfWork.CategoryRepository.PatchCategories(check.Items.SelectMany(i => i.Categories).Select(c => c.Name));
		    // TODO: uncomment
            //this.unitOfWork.ShopRepository.PatchShop(check.ShopName);

			var or = this.unitOfWork.CheckRepository.AddNewCheck(check);
			object data;
			if (or.Success)
			{
				data = "Method executed successfuly";
			}
			else
			{
				data = or.Exception.Message;
			}
            return new JsonResult() {Data = data, ContentType = @"application\json"};
		}

        public ActionResult UpdateSettings()
		{
            // TODO: implement unsuccessful operation result handling.
            var model = new UpdateSettingsModel { Settings = this.unitOfWork.AccountRepository.GetCurrentUserSettings().Result.ToClientSettings() };

		    return this.View(model);
		}

		[HttpPost]
		public bool SaveSettingsAjax(client.Settings settings)
		{
            var saveResult = this.unitOfWork.AccountRepository.UpdateUserSettings(settings.ToServerSettings());
		    CurrentUserHelper.SetCurrentUser(CurrentUserHelper.Username, CurrentUserHelper.Username, this.unitOfWork);
            // TODO: add messages to pool.
		    return saveResult.Success;
		}

		[HttpGet]
		[AllowAnonymous]
		public string Test()
		{
			return this.unitOfWork.AccountRepository.GetUser("user").Result.Settings.Email;
		}
	}
}